$(function() {
//Pagination.
    $page.init();
    $product.init();
    //////
    $('input.date').datepicker();
    $('#dialog_add').dialog({
        autoOpen: false,
        height: 600,
        width: 800,
        modal: true,
        resizable: false,
        draggable: true,
        buttons: {
            Add: function() {
                $product.Add();
            },
            Reset: function() {
                $product.resetFormAdd();
            },
            Cancel: function() {
                $product.resetFormAdd();
                $(this).dialog("close");
            }
        },
        close: function() {
        }
    });
    $('#dialog_del_user').dialog({
        autoOpen: false,
        width: 500,
        height: 400,
        modal: true,
        buttons: {
            Ok: function() {

            },
            Cancel: function() {
                $(this).dialog('close');
            }
        }
    });
    $('#dialog_upload_image').dialog({
        autoOpen: false,
        width: 300,
        height: 150,
        modal: true,
        buttons: {
            Upload: function() {
                $('#form_image_product').submit();
            },
            Cancel: function() {

                $product.resetUploadImgInput();
                $(this).dialog('close');
            }
        }
    });
    $('#dialog_product_detail').dialog({
        autoOpen: false,
        modal: true
    });
    $('input.add').click(function() {
        $('#dialog_add').dialog("open");
    });
    $('input.delete').click(function() {
        $('#dialog_del_user').dialog('open');
    });
    $('input#product_image_btn').click(function() {
        $('#dialog_upload_image').dialog('open');
    });
    //Tooltip
    $('#username, #email, #pass2').tooltip();
    //Vertical tabs.
    $("#dialog_add").tabs().addClass("ui-tabs-vertical ui-helper-clearfix");
    $("#dialog_add li").removeClass("ui-corner-top").addClass("ui-corner-left");
    //Add more input link to product detail section....
    $('#more_input').click(function() {
        $('.product-links').append($('.product-links .input-link').clone()[0]);
    });
    //View detail product.
    $('table.table-content tr.even, table.table-content tr.odd').click(function(event) {
        if (event.target.nodeName != 'A') {
            $('#dialog_product_detail').dialog('open');
        }
    });
    //Show popup edit.
    $('tr td a.edit').click(function(event) {
        event.preventDefault();
        $('#dialog_add').dialog("open");
    });
    //product category tree view 
    $("#product_category_tree").treeview();
    //Uload image when add new product.
    $product.uploadImage();
    // Initialize TinyMCE with and listbox
    tinyMCE.init({
        plugins: '-example', // - tells TinyMCE to skip the loading of the plugin
        mode: "exact",
        elements: 'product_description',
        theme: "advanced",
        theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,forecolor,backcolor",
        theme_advanced_buttons3: "hr,removeformat,visualaid,|,sub,sup,|,charmap",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        theme_advanced_statusbar_location: "bottom",
        width: "600",
        height: "500"
    });
});
var $tut = {
    token_name: 'token_name',
    token_value: 'token_value',
    ajax: function($option) {
        $option.data.tut_token = $('#' + this.token_value).val();
        $.ajax($option);
    }
};
var $product = {
    fields: {
        name: 'product_name',
        order: 'product_order',
        level: "product_level",
        language: 'product_language',
        status: 'status',
        featured: 'featured',
        summary: 'product_summary',
        description: 'product_description_slave',
        meta_title: 'product_meta_title',
        meta_keyword: 'product_meta_keyword',
        meta_description: 'product_meta_description',
        meta_robot: 'product_meta_robot',
        image: 'product_image',
        source: 'product_source'
    },
    message: 'error-message',
    actionGetList: '#url_getList',
    init: function() {
        this.getList(0);
        return this;
    },
    proccessErrorAdd: function($aError) {
        $product.resetFieldAdd();
        $aError = eval('(' + $aError + ')');
        for ($error in $aError) {
            $('#' + $product.fields[$error])
                    .after($aError[$error])
                    .css('border', '1px solid red');
            if ($aError[$error] == '') {
                $('#' + $product.fields[$error])
                        .css('border', '');
            }

            $('.' + $product.message)
                    .html($('input#error_message_add').val())
                    .show()
                    .fadeOut(5000, function() {
                $(this).empty();
            });
//            setTimeout(function(){
//                $('.' + $product.message)
//                    .hide()
//                    .empty();
//            },3000);
        }
    },
    resetFieldAdd: function() {
        $('.' + $product.message).empty();
        for ($field in $product.fields) {
            $('#' + $product.fields[$field])
                    .css('border', '');
            $('#' + $product.fields[$field] + '+ div.error').remove('div.error');
        }

//Reset error message of image field.
        $('#' + $product.fields.image + '~ div.error').remove('div.error');
    },
    resetUploadImage: function() {
        $('div.upload-image-product + div.error').remove('div.error');
    },
    resetUploadImgInput: function() {
        $('#form_image_product').get(0).reset();
        $('div.upload-image-product + div.error').remove('div.error');
    },
    resetFormAdd: function() {
        $('#form_add').get(0).reset();
        $product.resetFieldAdd();
        $('#product_image').val('');
        $('#product_image + img').remove('img');
        $('#product_image + br').remove('br');
        //reset error of image field.
        $('#product_image ~ .error').remove('div');
    },
    Add: function() {
        tinyMCE.triggerSave();
        var $option = {
            type: 'post',
            url: $('#form_add').attr('action'),
            dataType: 'json',
            data: $('#form_add').serialize(),
            success: function($response, $status) {
                if ($response.result) {
                    location.reload();
                }
                else {
                    $product.proccessErrorAdd($response.data);
                }

            }
        };
        $.ajax($option);
    },
    uploadImage: function() {
        $('#form_image_product').ajaxForm(
                {
                    success: function($response) {
                        $response = eval('(' + $response + ')');
                        if ($response.result) {
                            $('div#dialog_upload_image').dialog('close');
                            $product.createImage($response.data);
                            $product.resetUploadImgInput();
                            return true;
                        }

//Reset.
                        $product.resetUploadImage();
                        $('div.upload-image-product').after($response.message);
                    },
                    complete: function($xhr) {
                    }
                });
    },
    createImage: function($object) {
        if ($object == '' || $object == 'undefined') {
            return false;
        }

        $object = eval('(' + $object + ')');
        $('#product_image').siblings('img').remove('img');
        $('#product_image')
                .val($object.file_name)
                .after("<img src='" + $object.obsolute_path_new_image + "' height='100px' width='100px' alt='' /><br />");
        return true;
    },
    getList: function($offset) {
        var $link = $(this.actionGetList).val() + "/1";
        if ($offset) {
            $link = $(this.actionGetList).val() + "/" + $offset;
        }
        var $option = {
            type: 'post',
            url: $link,
            dataType: 'json',
            data: {},
            success: function($response, $status) {
                if ($response.result) {
                    $product.createList($response.data);
                }
            }
        };
        $tut.ajax($option);
        return this;
    },
    createList: function($productDataList) {
//        var data = JSON.parse($productDataList.data);
        var $data = $productDataList;
        var $body = $('#list');
        $body.empty();
        var tr = '<tr id = "row_{product_id}" class="{type}">' +
                '< td class = "center" >' +
                '< input type = "checkbox" name = "delete[]" id = "{product_id}" / >' +
                '< /td>' +
                '< td > {product_name} < /td>' +
                '< td class = "center" > {page_stutus}< /td>' +
                '< td class = "center" > {page_featured} < /td>' +
                '< td > {product_category} < /td>' +
                '< td > {product_level} < /td>' +
                '< td class = "right" > {product_order} < /td>' +
                '< td > {product_date} < /td>' +
                '< td > {language} < /td>' +
                '< td class = "right" > {product_id}< /td>' +
                '< td > < a href = "#" class = "edit" > Edit < /a></td >' +
                '< /tr>';

        for (var $i = 0; $i < $data.length; $i++) {
            var $row = $data[$i];
            var $productId = null;
            for (var $col in $row) {
                if ($col == 'mPageId') {
                    pageId = row[col];
                    tr = tr.replace(/{page_id}/g, pageId);
                } else if (col == 'mPageTitle') {
                    tr = tr.replace(/{page_title}/g, row[col]);
                } else if (col == 'mFullPath') {
                    tr = tr.replace(/{fullpath}/g, row[col]);
                } else if (col == 'mPageUrl') {
                    tr = tr.replace(/{tempfullpath}/g, row[col]);
                } else if (col == 'mIsActive') {
                    active = row[col];
                    tr = tr.replace(/{active}/g, active ? 'checked="checked"' : '');
                }
            }
            //Add row and register the event hanlder for action
            body.append($(tr));
            if (i % 2) {
                $('#row-' + pageId).addClass('even');
            }
            $('#uxEdit-' + pageId).click(Edit.bindEvent(null, pageId));
            $('#uxRemove-' + pageId).click(Delete.bindEvent(null, pageId));
        }
        $('#no-row').remove();
        if (0 == data.rows.length) {
            $('#uxPage').val(0);
            $('#body-ext_page').append($('<tr id="no-row"><td colspan="3">' + Js.no_item + '.</td></tr>'));
        }
        paging.reLoad($('#uxPage').val(), data.totalPage);
        $('.fullPath').each(function() {
            var id = this.id.split('-');
            var pageId = id[1];
            $(this).click(function(event) {
                $('#uxFullPathDialog').dialog('open');
                sStr = $('#fullpathtext-' + pageId).val();
                sLang = sStr.split('/');
                $('#uxTempPath').val('http://' + $('#hotel_id').val() + '.htss.worldhotel-link.net/' + sLang[3] + '/' + $('#tempfullpath-' + pageId).val());
                if ($('#uxTempPath').val() != $('#fullpathtext-' + pageId).val())
                    $('#uxFullPath').val($('#fullpathtext-' + pageId).val());
            });
        });
    }
};
var $page = {
    action: '#url_pagination',
    class: 'page',
    container: '#pagination',
    content: '',
    init: function() {
        this._get()
                .pageEvent();
    },
    pageEvent: function() {
        $('.' + this.class).live('click', function($event) {
            $event.preventDefault();
            var $link = $(this).attr('href');
            var $option = {
                type: 'post',
                url: $link,
                dataType: 'json',
                data: {},
                success: function($response, $status) {
                    if ($response.result) {
                        $page.create($response.data)
                                .addClass(this.class);
                        $product.getList($response.other);
                    }
                }
            };
            $tut.ajax($option);
        });
        return this;
    },
    _get: function() {
        var $option = {
            type: 'post',
            url: $(this.action).val(),
            dataType: 'json',
            data: {},
            success: function($response, $status) {
                if ($response.result) {
                    $page.create($response.data)
                            .addClass(this.class);
                }
            }
        };
        $tut.ajax($option);
        return this;
    },
    create: function($data) {
//        this.content = JSON.parse($data);
        this.content = $data;
        $(this.container).empty()
                .append(this.content);
        return this;
    },
    addClass: function() {
        $(this.container + ' a').addClass(this.class);
        return this;
    }
};